package com.xiubai.appforpda.activitys;

import android.app.Dialog;
import android.content.Intent;
import android.nfc.tech.IsoDep;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.Toast;

import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.xiubai.appforpda.R;
import com.xiubai.appforpda.adapter.ReturnEquipmentAdapter;
import com.xiubai.appforpda.db.DatabaseUtils;
import com.xiubai.appforpda.entity.SQLDevicesReturnBean;
import com.xiubai.appforpda.entity.SQLPamAssetBean;
import com.xiubai.appforpda.entity.TestCheckAssetsBean;
import com.xiubai.appforpda.jack.utils.AppConstants;
import com.xiubai.appforpda.jack.utils.DateUtils;
import com.xiubai.appforpda.jack.utils.Trace;
import com.xiubai.appforpda.utils.ClickUtil;
import com.xiubai.appforpda.utils.DisplayUtil;
import com.xiubai.appforpda.utils.ScreenUtils;
import com.xiubai.appforpda.widget.CustomDialog;
import com.xiubai.appforpda.widget.CustomDialogListener;
import com.xiubai.appforpda.widget.pull.PullToRefreshView;

import java.util.ArrayList;
import java.util.List;

import static com.xiubai.appforpda.activitys.MainActivity.REQUEST_CAMERA_PERM;
import static com.xiubai.appforpda.activitys.MainActivity.REQUEST_CODE;

public class ReturnEquipmentActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemLongClickListener {


    private View btn_confirm_return;
    private CustomDialog returnDialog;
    private ArrayList<TestCheckAssetsBean> checkAssetsBeans;
    private View btn_setting;
    private View btn_test;
    private PullToRefreshView lv_return_content;
    private TextView tv_name;
    private View btn_the_user;
    private View btn_scan;
    private String result;
    private boolean is_have = false;
    private ReturnEquipmentAdapter returnEquipmentAdapter;
    private CustomDialog successDialog;
    private boolean first = true;
    private ArrayList<SQLDevicesReturnBean> testBeans = new ArrayList<>();
    private View btn_back;
    private View btn_continue_scan;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_return_equipment_promt);

        tv_name = (TextView) findViewById(R.id.tv_name);
        tv_name.setText("经办人: " + AppConstants.USER_NAME);
        btn_scan = findViewById(R.id.btn_scan);
        btn_scan.setOnClickListener(this);
        btn_back = findViewById(R.id.btn_back);
        btn_back.setOnClickListener(this);

    }

    private void initPromt() {
        if (first) {
            setContentView(R.layout.activity_return_equipment);
            initView();
            initData();
            first = false;
        } else {
            addData();
        }
    }

    private void addData() {
        boolean isNotUse = false;// 如果归还的设备不是在用状态,需给出特殊提示
        List<SQLPamAssetBean> beans = DatabaseUtils.getHelper().queryAll(SQLPamAssetBean.class);
        if (beans != null) {
            for (SQLPamAssetBean child : beans) {
                if (!is_have) {
                    if (child.getAssetcode().equals(result)) {
                        is_have = true;
                        if(!"Y".equals(child.getStacode())){
                            isNotUse = true;
                            break;
                        }

                        SQLDevicesReturnBean testBean = new SQLDevicesReturnBean();
                        testBean.assetcode = child.getAssetcode();
                        testBean.audtcode = AppConstants.USER_CODE;
                        testBean.billdate = DateUtils.getStringDateShort();
                        testBean.assetname = child.getAssetname();
                        if (!testBeans.contains(testBean)) {
                            testBeans.add(testBean);
                        }

                    }
                }
            }
        }
        if(isNotUse){
            dialogDismiss(successDialog);
            showSuccessDialog("该设备在ERP中未办理领用/借用流程，无需归还", "继续", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(ClickUtil.isFastDoubleClick()) {
                        return;
                    }
                    startScan();
                }
            });
            return;
        }
        if (!is_have) {
            dialogDismiss(successDialog);
            showSuccessDialog("没有查询到相关的资产", "继续", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(ClickUtil.isFastDoubleClick()) {
                        return;
                    }
                    startScan();
                }
            });
            return;
        }
        if (returnEquipmentAdapter != null) {
            returnEquipmentAdapter.notifyDataSetChanged();
        }
        dialogDismiss(successDialog);
        showSuccessDialog("是否继续扫描", "继续", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(ClickUtil.isFastDoubleClick()) {
                    return;
                }
                dialogDismiss(successDialog);
                startScan();
            }
        });

      /*  handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                startScan();
            }
        }, 1500);*/
    }

    private static Handler handler = new Handler();

    private void dialogDismiss(Dialog dialog) {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }


    /**
     * 显示抓取成功
     */
    private void showSuccessDialog(String message, String buttonName, View.OnClickListener listener) {
        successDialog = new CustomDialog(this, new CustomDialogListener() {
            @Override
            public void onDialogClosed(int closeType) {

            }
        });
        successDialog.setView(LayoutInflater.from(this).inflate(R.layout.single_button_layout, null));
        TextView tv_input = (TextView) successDialog.findId(R.id.tv_single_message);
        TextView btn_data_confirm = (TextView) successDialog.findId(R.id.btn_data_confirm);
        View btn_data_return = successDialog.findId(R.id.btn_data_return);
        if (btn_data_return != null) {
            btn_data_return.setVisibility(View.VISIBLE);
            btn_data_return.setOnClickListener(this);
        }
        if (btn_data_confirm != null) {
            btn_data_confirm.setText(buttonName);
            btn_data_confirm.setOnClickListener(listener);
        }
        if (tv_input != null) {
            tv_input.setText(message);
        }
        successDialog.setCanceledOutside(false);
        successDialog.setCancelable(false);
        successDialog.show();

        dialogMatchWindow(successDialog);
    }

    private void dialogMatchWindow(Dialog dialog) {
        Window window = dialog.getWindow();
        window.setGravity(Gravity.CENTER);
        window.getDecorView().setPadding(0, 0, 0, 0);

        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = DisplayUtil.dip2px(300, this.getResources().getDisplayMetrics().density);
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);
    }

    private void startScan() {
        is_have = false;
        Intent intent4 = new Intent(ReturnEquipmentActivity.this, CaptureActivity.class);
        startActivityForResult(intent4, REQUEST_CODE);
    }

    private void initData() {
        testBeans.clear();
        returnEquipmentAdapter = new ReturnEquipmentAdapter(this, testBeans);
        lv_return_content.setAdapter(returnEquipmentAdapter);

        addData();
    }

    private void initView() {

        TextView tv_in_name = (TextView) findViewById(R.id.tv_in_name);
        tv_in_name.setText("经办人: " + AppConstants.USER_NAME);
        btn_confirm_return = findViewById(R.id.btn_confirm_return);
        lv_return_content = (PullToRefreshView) findViewById(R.id.lv_return_content);
        btn_confirm_return.setOnClickListener(this);
        findViewById(R.id.btn_confirm_back).setOnClickListener(this);

        tv_name = (TextView) findViewById(R.id.tv_name);
        btn_continue_scan = findViewById(R.id.btn_continue_scan);
        btn_continue_scan.setOnClickListener(this);
        lv_return_content.setOnItemLongClickListener(this);
    }

    @Override
    public void onClick(View view) {
        if(ClickUtil.isFastDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.btn_confirm_return:
                if(testBeans.isEmpty()) {
                    Toast.makeText(this, "没有需要归还的资产!", Toast.LENGTH_SHORT).show();
                    return;
                }
                doReturnEquipment();
                break;
            case R.id.btn_return_complete:
                if (returnDialog != null && returnDialog.isShowing()) {
                    returnDialog.dismiss();
                    finish();
                }
                break;

            case R.id.btn_scan:
                startScan();
                break;

            case R.id.btn_continue_scan:
                startScan();
                break;

            case R.id.btn_data_return:
                dialogDismiss(successDialog);
                break;
            case R.id.btn_back:
            case R.id.btn_confirm_back:
                finish();
                break;
        }
    }

    /**
     * 归还设备
     */
    private void doReturnEquipment() {
        for(SQLDevicesReturnBean bean : testBeans) {
            DatabaseUtils.getHelper().save(bean);
        }
        returnDialog = new CustomDialog(this, new CustomDialogListener() {
            @Override
            public void onDialogClosed(int closeType) {

            }
        });
        returnDialog.setView(LayoutInflater.from(this).inflate(R.layout.return_dialog_layout, null));
        View btn_return_complete = returnDialog.findId(R.id.btn_return_complete);
        if (btn_return_complete != null) {
            btn_return_complete.setOnClickListener(this);
        }
        returnDialog.setCanceledOutside(false);
        returnDialog.setCancelable(false);
        returnDialog.show();

        dialogMatchWindow();
    }

    private void dialogMatchWindow() {
        Window window = returnDialog.getWindow();
        window.setGravity(Gravity.CENTER);
        window.getDecorView().setPadding(0, 0, 0, 0);

        WindowManager.LayoutParams lp = window.getAttributes();
        int screenWidth = ScreenUtils.getScreenWidth(this);
//        PixelDpHelper.dip2px(this, )
        lp.width = (int) (screenWidth * 0.90f);
//        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        /**
         * 处理二维码扫描结果
         */
        if (requestCode == REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    result = bundle.getString(CodeUtils.RESULT_STRING);
                    Trace.d("result" + result);
//                    Toast.makeText(this, "解析结果:" + result, Toast.LENGTH_LONG).show();
                    initPromt();
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(ReturnEquipmentActivity.this, "解析二维码失败", Toast.LENGTH_LONG).show();
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_BACK) {
                    Trace.d("stop");
                }
            }
        } else if (requestCode == REQUEST_CAMERA_PERM) {
            Toast.makeText(this, "从设置页面返回...", Toast.LENGTH_SHORT)
                    .show();
        }
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        final SQLDevicesReturnBean item = (SQLDevicesReturnBean) parent.getAdapter().getItem(position);
        if (item == null) {
            return true;
        }

        showSuccessDialog("需要删除此条记录吗?", "确认", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(ClickUtil.isFastDoubleClick()) {
                    return;
                }
                dialogDismiss(successDialog);
                testBeans.remove(item);
                returnEquipmentAdapter.notifyDataSetChanged();
            }
        });
        return true;
    }
}
